package com.oly.cms.web.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.oly.cms.common.model.properties.OlyThemeConfigProperties;
import com.grace.common.core.domain.AjaxResult;
import com.grace.common.utils.StringUtils;
import com.grace.common.utils.ip.IpUtils;

import java.util.Arrays;
import com.oly.cms.general.service.taglib.ConfigTag;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** 指定某些管理IP才能访问某些控制方法 */
@Component
public class IPInterceptor implements HandlerInterceptor {

    @Autowired
    private ConfigTag configServiceImpl;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 过滤ip,若用户在白名单内，则放行
        String ipAddress = IpUtils.getIpAddr(request);
        String ips = configServiceImpl.getKeyDefault(
                OlyThemeConfigProperties.THEME_CONFIG_GROUP.defaultValue(),
                OlyThemeConfigProperties.THEME_MANGER_ALLOW_IP);
        if (StringUtils.isEmpty(ips)) {
            return true;
        } else if (Arrays.asList(StringUtils.split(ips)).contains(ipAddress)) {
            return true;
        } else {
            response.getWriter().println(AjaxResult.error("该地址不允许访问!"));
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }
}
